package com.singfan.core.dao.database.impl;

import com.singfan.common.db.DaoBaseGeneric;
import com.singfan.common.db.DbContext;
import com.singfan.common.db.PrimaryKeyBuilder;
import com.singfan.core.dao.database.IShopDao;
import com.singfan.core.dao.database.model.Shop;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 *
 * Author: hansonghe
 * Date: 2015-08-19 12:12
 * Desc:
 */
@Repository
public class ShopDaoImpl extends DaoBaseGeneric<Shop> implements IShopDao {
    @Override
    protected String getTableName(Object hashKey) {
        return tableNameBase;
    }

    @Override
    protected String getDatabaseId(Object hashKey) {
        return "app_1";
    }

    @Override
    public void create(Shop shop) {
        if (shop.getId() <= 0) {
            long shopId = PrimaryKeyBuilder.getInstance().build(DbContext.getDbConfigProvider().getTable(tableNameBase).getId(), getTableNewestVersion());
            shop.setId(shopId);
        }
        insert(null, shop);
    }

    @Override
    public Shop selectShop(long shopId) {
        return selectByPK(shopId, shopId);
    }

    @Override
    public Shop selectShop(String phoneNumber) {
        String sql = "SELECT * FROM " + getTableName(null) + " WHERE register_phone=?";
        return selectOne(null, sql, phoneNumber);
    }

    @Override
    public List<Shop> selectAll() {
        String sql = "SELECT * FROM " + getTableName(null);
        return selectList(null, sql);
    }

    @Override
    public void updatePwd(long shopId, String pwd, String pwdSalt) {
        String sql = "UPDATE " + getTableName(null) + " SET password=?, password_salt=? WHERE id=?";
        execute(null, sql, pwd, pwdSalt, shopId);
    }

    @Override
    public List<Shop> selectSlaveShopList(int masterShopId) {
        String sql = "SELECT * FROM " + getTableName(null) + " WHERE master_shop_id=?";
        return selectList(null, sql, masterShopId);
    }

    @Override
    public boolean isExistShopByName(int masterShopId, String slaveShopName) {
        String sql = "SELECT id FROM " + getTableName(null) + " WHERE master_shop_id=? AND slave_shop_name=?";
        return isExist(null, sql, masterShopId, slaveShopName);
    }

    @Override
    public boolean isExistShopByPhone(String phone) {
        String sql = "SELECT id FROM " + getTableName(null) + " WHERE register_phone=?";
        return isExist(null, sql, phone);
    }

    @Override
    public void update(Shop shop) {
        updateByPK(null, shop);
    }

    @Override
    public void updateStatus(long shopId, int status) {
        String sql = "UPDATE " + getTableName(null) + " SET status=? WHERE id=?";
        execute(null, sql, status, shopId);
    }

    @Override
    public void resetPwd(long shopId, String pwd, String salt) {
        String sql = "UPDATE " + getTableName(null) + " SET password=?, password_salt=? WHERE id=?";
        execute(null, sql, pwd, salt, shopId);
    }
}
